package com.xchb.im.server.service.impl;

import com.xchb.im.common.algorithm.RouteHandle;
import com.xchb.im.server.config.AppConst;
import com.xchb.im.server.entity.po.NodeInfoVo;
import com.xchb.im.server.service.ConnectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author XDD
 * @project muchat
 * @date 2021/7/24
 * @description Good Good Study,Day Day Up.
 */
@Service
public class ConnectionServiceImpl implements ConnectionService {

    @Autowired
    private RouteHandle routeHandle;

    @Override
    public List<NodeInfoVo> nodeList() {
        List<NodeInfoVo> list = AppConst.NODE_LIST.stream().map(str -> {
            return assembleNode(str);
        }).collect(Collectors.toList());
        return list;
    }

    @Override
    public NodeInfoVo node() {
        String server = routeHandle.routeServer(new ArrayList<>(AppConst.NODE_LIST),"x");
        if(server==null){
            return null;
        }
        NodeInfoVo infoVo = assembleNode(server);

        return infoVo;
    }

    private NodeInfoVo assembleNode(String server) {
        String[] split = server.split(":");
        NodeInfoVo node = new NodeInfoVo();
        node.setProtocol("ws");
        node.setIp(split[0]);
        node.setPort(split[1]);
        return node;
    }
}
